package org.budo.redis.jdbc.driver.statement.hash;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.redis.jdbc.driver.BudoRedisJdbcConnection;
import org.budo.redis.jdbc.driver.BudoRedisJdbcPreparedStatement;
import org.budo.redis.jdbc.driver.executor.RedisStatementExecutor;
import org.budo.redis.jdbc.driver.statement.AbstractRedisStatement;

/**
 * 使用 Mybatis 时候，由于PropertyTokenizer的原因，返回值中的key如果包含点，则会被理解为层次级别
 * 
 * @author lmw
 * @see org.apache.ibatis.reflection.property.PropertyTokenizer
 */
public class HGETALL extends AbstractRedisStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException{
        byte[] key = this.parameter(0, preparedStatement);

        RedisStatementExecutor statementExecutor = ((BudoRedisJdbcConnection) preparedStatement.getConnection()).getStatementExecutor();
        Map<byte[], byte[]> map = statementExecutor.hgetAll(key);

        byte[][] columnNameBytes = map.keySet().toArray(new byte[map.size()][]);
        String[] columnNames = new String[columnNameBytes.length];
        for (int i = 0; i < columnNameBytes.length; i++) {
            columnNames[i] = new String(columnNameBytes[i]);
        }

        ResultSet resultSet = new MapArrayResultSet(columnNames, new Map[] { map });
        ((BudoRedisJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}